<!-- 员工添加 -->
<template>
  <div>
    <el-card style="width: 98%; margin: 0 auto; margin-top: 10px">
      <el-form
        ref="ruleFormRef"
        style="max-width: 400px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="员工头像:" prop="photo">
          <el-upload class="avatar-uploader" :action="imageUrl" :show-file-list="false" :headers="headers"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="ruleForm.photo" :src="imgUrl + ruleForm.photo" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="员工姓名:" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入员工姓名" />
        </el-form-item>
        <el-form-item label="联系方式:" prop="mobile">
          <el-input v-model="ruleForm.mobile" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="身份证号:" prop="idCard">
          <el-input v-model="ruleForm.idCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="所属部门:" prop="departmentName">
          <el-cascader
            v-model="ruleForm.departmentId"
            :options="departmentList"
            :props="props"
            style="width: 100%"
            @change="handleChange"
          />
        </el-form-item>
        <el-form-item label="所属岗位:" prop="roleIds">
          <el-select v-model="ruleForm.roleIds" multiple placeholder="请选择" @change="checkRoles">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="账号:" prop="adminUserName">
          <el-input v-model="ruleForm.adminUserName" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码:" prop="adminPwd">
          <el-input v-model="ruleForm.adminPwd" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="是否护工:" prop="isCarer">
          <el-radio-group v-model="ruleForm.isCarer">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </el-card>

    <div class="btn">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import type { FormInstance, FormRules, UploadProps } from "element-plus";
import { getToken } from "@/utils/auth";
import { staffAdd, staffGet, staffUpdate } from '@/api/personel/staff/staff'
import { getDepartmentList } from '@/api/personel/department/department'
import { RoleList } from '@/api/personel/position/position'
import { listData, listParams } from '@/api/personel/position/type'
import { staffListData } from '@/api/personel/staff/type'
import { buildTree } from '@/utils/treeUtil'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()


// 获取单条数据
let ruleForm = reactive<staffListData>({
  id: 0,
  companyId: 0,
  photo: "",
  name: "",
  mobile: "",
  isCarer: 0,
  departmentId: 0,
  addAccountId: 0,
  addAccountName: "",
  addTime: "",
  departmentName: "",
  roles: [],
  roleIds: [],
  adminId: 0,
  adminUserName: "",
  adminPwd: "",
  enable: 0,
  idCard: "",
});
const staffId = ref();
const getStaff = async () => {
  let res = await staffGet(staffId?.value);
  Object.assign(ruleForm, res);
  // console.log(111, ruleForm);
  ruleForm.roleIds = res.roles.map((item: any) => item.id);
};

// 修改
const upload = async () => {
  let res = await staffUpdate(ruleForm);
  ElMessage.success("修改成功");
  router.push("/personel/Staff");
};

// 获取岗位列表
const RoleParams = reactive<listParams>({
  page: 1,
  pageSize: 1000,
});

interface optionsValue {
  value: string;
  label: string;
}
const options = reactive<optionsValue[]>([]);
const getList = async () => {
  let res = await RoleList(RoleParams);
  // console.log('岗位列表', res);
  res.list.forEach((item: listData) => {
    options.push({
      value: item.id as unknown as string,
      label: item.name,
    });
  });
};
const checkRoles = (value: number[]) => {
  let arr = value.map((item: number) => ({ id: item }));
  ruleForm.roles = arr;
};

// 部门列表
const props = {
  label: "name",
  value: "id",
};
const handleChange = (value: any) => {
  ruleForm.departmentId = value[value.length - 1];
};
const departmentList = ref([]);
const getDepartList = async () => {
  let res = await getDepartmentList();
  // console.log('部门列表', res);
  departmentList.value = buildTree(res.list);
};

// 添加
const submitForm = async () => {
  const formToSubmit = {
    ...ruleForm,
    mobile: Number(ruleForm.mobile),
    isCarer: String(ruleForm.isCarer),
  };
  let res = await staffAdd(formToSubmit);
  ElMessage.success("添加成功");
  router.push("/personel/Staff");
};
const submit = async () => {
  ruleFormRef.value?.validate(async (valid) => {
    if (valid) {
      ruleForm.id === 0 ? await submitForm() : await upload();
    }
  });
};

// 取消
const cancel = () => {
  router.push("/personel/Staff");
};

// 上传图片
const imageUrl = import.meta.env.VITE_APP_API_URL + "/api/upload/add" // 图片根路径
const imgUrl = import.meta.env.VITE_IMG_URL //获取图根路径
const headers = { 'Authorization': getToken() }

const handleAvatarSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  ruleForm.photo = response.data.url;
};
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (
    rawFile.type !== "image/jpeg" &&
    rawFile.type !== "image/png" &&
    rawFile.type !== "image/webp"
  ) {
    ElMessage.error("只能上传jepg/png/webp格式的图片!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("上传的图片大小不能超过2MB!");
    return false;
  }
  return true;
};

// 表单校验
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<staffListData>>({
  name: [{ required: true, message: "请输入员工姓名", trigger: "blur" }],
  photo: [{ required: true, message: "请选择上传的头像", trigger: "blur" }],
  mobile: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    { pattern: /^[0-9]{11}$/, message: "手机号码格式不正确", trigger: "blur" },
  ],
  idCard: [{ required: true, message: "请输入身份证号", trigger: "blur" }],
  adminPwd: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
  adminUserName: [{ required: true, message: "请输入账号", trigger: "blur" }],
  isCarer: [
    {
      required: true,
      message: "请选择是否是护工",
      trigger: "change",
    },
  ],
});

onMounted(() => {
  getList();
  getDepartList();
  staffId.value = route.query.id;
  getStaff();
});
</script>

<style scoped lang="less">
.btn {
  display: flex;
  justify-content: center;
  margin: 40px 0 40px 0;
}
</style>
<style>
.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  width: 80px;
  height: 80px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}

.avatar {
  width: 80px;
  height: 80px;
}
</style>
